package com.stwyj.sbd.advice;

import com.stwyj.sbd.common.AppErrors;
import com.stwyj.sbd.config.exception.ResultErrorException;
import com.stwyj.sbd.config.handler.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>
 * 异常增强、统一返回错误消息
 * Exception                               HTTP Status Code
 * ConversionNotSupportedException         500 (Internal Server Error)
 * HttpMessageNotWritableException         500 (Internal Server Error)
 * HttpMediaTypeNotSupportedException      415 (Unsupported Media Type)
 * HttpMediaTypeNotAcceptableException     406 (Not Acceptable)
 * HttpRequestMethodNotSupportedException  405 (Method Not Allowed)
 * NoSuchRequestHandlingMethodException    404 (Not Found)
 * TypeMismatchException                   400 (Bad Request)
 * HttpMessageNotReadableException         400 (Bad Request)
 * MissingServletRequestParameterException 400 (Bad Request)
 * BindException                           400 (Bad Request)
 * </p>
 *
 * 在注解ResponseStatus中可定义返回状态码，不添加该注解走默认
 *
 * @author stwyj
 * @since 2018/11/30
 */
@RestControllerAdvice
@Slf4j
public class CommonExceptionHandler {

    /**
     * 通用错误返回结果处理
     * @param ex 异常信息
     * @return 统一处理结果
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(ResultErrorException.class)
    public ResponseResult validatorException(ResultErrorException ex) {
        return new ResponseResult(ex.getCode(), ex.getMessage(), null);
    }

    /**
     * MethodArgumentNotValidException处理
     * @param ex 异常信息
     * @return 统一处理结果
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseResult methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        return new ResponseResult(AppErrors.ERROR_PARAMS_IS_WRONG.code(), ex.getBindingResult().getAllErrors().get(0).getDefaultMessage(), null);
    }

}
